<template>
  <div style="display: flex; flex-direction: column ;width: 100%">
<!--    <div style="float: right; margin: 10px">-->
<!--      <el-button @click="Greets">新增</el-button>-->
<!--    </div>-->
<!--    <el-card style="margin-bottom: 10px">-->
<!--      <el-button @click="Greets">新增</el-button>-->
<!--    </el-card>-->
    <el-card style="height: 100%">
<!--      <div  style="float: right;margin-bottom: 10px">-->
<!--        <el-button color="rgb(77, 112, 255)" @click="Greets">新增</el-button>-->
<!--      </div>-->
      <el-table
          :data="tableData"
          style="width: 100%"
          :cell-style="{ textAlign: 'center' }"
          :header-cell-style="{ 'text-align': 'center', 'background-color': 'rgb(247, 251, 255)' }">
        <el-table-column
            v-if="false"
            prop="id"
            label="ID">
        </el-table-column>
        <el-table-column
            prop="name"
            label="名称">
        </el-table-column>
        <el-table-column
            prop="type"
            label="类型">
        </el-table-column>
        <el-table-column
            prop="address"
            label="地址">
          <template #default="{row}">
        <span>{{row.address + ':' + row.port}}</span>
          </template>
        </el-table-column>
        <el-table-column
            prop="username"
            label="用户名">
        </el-table-column>
        <el-table-column
            prop="database"
            label="数据库">
        </el-table-column>
        <el-table-column
            prop="remarks"
            label="备注">
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="140">
          <template #header>
            操作
            <el-button color="rgb(77, 112, 255)" @click="dialogFormVisible = true" size="small" style="margin-left: 3px">新增</el-button>
          </template>
          <template #default="{row}">
            <el-button link type="primary" size="small" @click="viewDetails(row)">
              查看
            </el-button>
            <el-button link type="primary" size="small" @click="updateDetail(row)">修改</el-button>
            <el-button link type="danger" size="small" @click="deleteData(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog v-model="dialogFormVisible" title="新增数据库" width="400px">
        <el-form :model="form" :rules="formRules" ref="formRef">
          <el-form-item label="数据库名称" :label-width="formLabelWidth" prop="name">
            <el-input v-model="form.name" autocomplete="off" clearable />
          </el-form-item>
          <el-form-item label="类型" :label-width="formLabelWidth" prop="type">
            <el-select v-model="form.type" placeholder="请选择数据库类型" >
              <el-option label="Oracle" value="Oracle" />
              <el-option label="MySQL" value="MySQL" />
            </el-select>
          </el-form-item>
          <el-form-item label="数据库地址" :label-width="formLabelWidth" prop="address">
            <el-input v-model="form.address" autocomplete="off" clearable />
          </el-form-item>
          <el-form-item label="端口" :label-width="formLabelWidth" prop="port">
            <el-input v-model="form.port" autocomplete="off" clearable />
          </el-form-item>
          <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
            <el-input v-model="form.username" autocomplete="off" clearable />
          </el-form-item>
          <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
            <el-input v-model="form.password" type="password" show-password autocomplete="off" clearable />
          </el-form-item>
          <el-form-item label="数据库" :label-width="formLabelWidth" prop="database">
            <el-input v-model="form.database" autocomplete="off" clearable />
          </el-form-item>
          <el-form-item label="备注" :label-width="formLabelWidth">
            <el-input v-model="form.remarks" autocomplete="off" clearable />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="validateAndSave">
<!--              dialogFormVisible = false-->
              保存
            </el-button>
          </div>
        </template>
      </el-dialog>
    </el-card>

    <el-dialog
        v-model="deleteConfirmVisible"
        title="删除确认"
        width="30%"
        :before-close="cancelDelete"
    >
      <p>您确定要删除这条记录吗？</p>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelDelete">取消</el-button>
        <el-button type="primary" @click="confirmDelete">确定</el-button>
      </span>
      </template>
    </el-dialog>

    <el-dialog v-model="updateDialogVisible" title="修改数据库" width="400px">
      <!-- 表单内容应与新增对话框相似，但绑定至editingRow -->
      <!-- 示例省略，请参考新增对话框的el-form配置，但v-model绑定应指向editingRow的相应属性 -->

      <el-form :model="editingRow" :rules="formRules" ref="formRef">
        <el-form-item label="数据库名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="editingRow.name" autocomplete="off" clearable />
        </el-form-item>
        <el-form-item label="类型" :label-width="formLabelWidth" prop="type">
          <el-select v-model="editingRow.type" placeholder="请选择数据库类型" >
            <el-option label="Oracle" value="Oracle" />
            <el-option label="MySQL" value="MySQL" />
          </el-select>
        </el-form-item>
        <el-form-item label="数据库地址" :label-width="formLabelWidth" prop="address">
          <el-input v-model="editingRow.address" autocomplete="off" clearable />
        </el-form-item>
        <el-form-item label="端口" :label-width="formLabelWidth" prop="port">
          <el-input v-model="editingRow.port" autocomplete="off" clearable />
        </el-form-item>
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
          <el-input v-model="editingRow.username" autocomplete="off" clearable />
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
          <el-input v-model="editingRow.password" type="password" show-password autocomplete="off" clearable />
        </el-form-item>
        <el-form-item label="数据库" :label-width="formLabelWidth" prop="username">
          <el-input v-model="editingRow.database" autocomplete="off" clearable />
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input v-model="editingRow.remarks" autocomplete="off" clearable />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="updateDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveEdit">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import {ref, watch, reactive, onMounted} from "vue";
// import { EventsOn } from "../../wailsjs/runtime/runtime"
// import { BrowserOpenURL  } from "/wailsjs/runtime/runtime"
import { BrowserOpenURL  } from "../../wailsjs/runtime/runtime"
import {CreateConnect, DeleteConnect, GetConnectList} from "../../wailsjs/go/main/App.js";
import { ElMessage } from "element-plus"
// import { Greet } from "../../wailsjs/go/main/App"
// const app = ref(window.go.main.App)
// const rt = ref(runtime.runtime)
const result = ref(0)

const tableData = ref([]);

const formRef = ref(null); // 添加表单引用

const dialogFormVisible = ref(false)
const formLabelWidth = '100px'
const form = reactive({
  name: '',
  type: '',
  address: '',
  port: '',
  username: '',
  password: '',
  database: '',
  remarks: ''
})

const formRules = {
  name: [{ required: true, message: '请输入数据库名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择数据库类型', trigger: 'change' }],
  address: [{ required: true, message: '请输入数据库地址', trigger: 'blur' }],
  port: [{ required: true, message: '请输入数据库端口', trigger: 'blur' }],
  username: [{ required: true, message: '请输入数据库用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入数据库密码', trigger: 'blur' }],
  database: [{ required: true, message: '请输入数据库', trigger: 'blur' }],
};

// 保存并验证表单
const validateAndSave = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      // 验证通过，执行保存逻辑
      dialogFormVisible.value = false;
      CreateConnect(form).then(res =>{
        if (res.code === 200){
          ElMessage.success('保存成功');
          GetConnectList().then(res => {
            if (res.code === 200) {
              tableData.value = res.data;
            }
          });
        }
      })
    } else {
      // 验证失败，弹出提示
      ElMessage.error('请填写完整表单项');
    }
  });
};
onMounted(() => {
  GetConnectList().then(res => {
    if (res.code === 200) {
      tableData.value = res.data;
    }
  });
});

function openUrl(url) {
  BrowserOpenURL(url)
}

// 查看详情
function viewDetails(row) {
    console.log(row.id);
}

// 控制删除确认对话框的显示
const deleteConfirmVisible = ref(false);

// 用于存储待删除行的信息
const selectedRow = ref({});

// 显示删除确认对话框
function showDeleteConfirm(row) {
  selectedRow.value = row;
  deleteConfirmVisible.value = true;
}

// 取消删除，关闭对话框
function cancelDelete() {
  deleteConfirmVisible.value = false;
  selectedRow.value = {};
}

// 确认删除，执行删除逻辑并关闭对话框
async function confirmDelete() {
  try {
    await DeleteConnect(selectedRow.value.id);
    ElMessage.success('删除成功');
    deleteConfirmVisible.value = false;
    // 根据实际情况，可能还需要刷新表格数据
    // 例如，如果tableData是响应式的，且在删除后需要更新，可以在这里调用刷新数据的方法
    var ra = await GetConnectList();
    tableData.value = ra.data;
  } catch (error) {
    ElMessage.error('删除失败，请重试');
  }
}

// 修改删除函数，以显示二次确认对话框
function deleteData(row) {
  showDeleteConfirm(row);
}



// 用于控制修改对话框的显示
const updateDialogVisible = ref(false);

// 当前选中行的副本，用于编辑
const editingRow = ref({});

// 显示修改对话框并填充数据
function updateDetail(row) {
  editingRow.value = {...row}; // 复制一行数据以避免直接修改原始数据
  updateDialogVisible.value = true;
}

// 保存修改后的数据
const saveEdit = async () => {
  try {
    // 这里假设有一个UpdateConnect函数用于更新数据
    // 请根据实际情况调整函数名和参数
    const response = await CreateConnect(editingRow.value);
    if (response.code === 200) {
      ElMessage.success('修改成功');
      updateDialogVisible.value = false;
      // 刷新表格数据
      var ra = await GetConnectList();
      tableData.value = ra.data;
    } else {
      ElMessage.error(response.message || '修改失败，请重试');
    }
  } catch (error) {
    ElMessage.error('修改过程中发生错误');
  }
};

// const Greets = () => {
//   Greet("aa").then(res => {
//     console.log(res)
//   })
// }
</script>

<!--<script>-->
<!--import {GetConnectList} from "../../wailsjs/go/main/App.js";-->

<!--export default {-->
<!--  methods: {-->
<!--    handleClick(row) {-->
<!--      console.log(row.zip);-->
<!--    }-->
<!--  },-->
<!--  created() {-->
<!--    GetConnectList().then(res => {-->
<!--      console.log(res)-->
<!--      if (res.code === 200){-->
<!--        this.tableData.value = res.data-->
<!--      }-->
<!--    })-->
<!--  },-->
<!--  // setup(){-->
<!--  //   GetConnectList().then(res => {-->
<!--  //     console.log(res)-->
<!--  //     if (res.code === 200){-->
<!--  //       this.tableData = res.data-->
<!--  //     }-->
<!--  //   })-->
<!--  // },-->
<!--  data() {-->
<!--    return {-->
<!--      // tableData: [-->
<!--      //   {-->
<!--      //     id: 1,-->
<!--      //     name: '数据库1',-->
<!--      //     type: 'mysql',-->
<!--      //     username: 'admin',-->
<!--      //     address: '127.0.0.1',-->
<!--      //     port: "80881",-->
<!--      //     remarks: "200333"-->
<!--      //   }-->
<!--      // ]-->
<!--    }-->
<!--  }-->
<!--}-->
<!--</script>-->

<style>

</style>